/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.managedbean;

import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author DOWN
 */
@Singleton
public class ConnectorService extends AbstractModule {

    @Override
    protected void configure() {
        bind(DbConnector.class);
    }

    @Provides
    @Singleton
    DbConnector connector() {
        return null;
    }

    static class DbConnector {

        public MongoClient client;
        public DB database;
        private ArrayList<DatabaseBean> databaseMap;

        public DbConnector() {
            try {
                client = new MongoClient("localhost", 27017);
                init();
            } catch (UnknownHostException ex) {
                Logger.getLogger(ConnectorService.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        public void init() {
            databaseMap = new ArrayList<DatabaseBean>();

            for (String dbName : client.getDatabaseNames()) {
                /*Set Current DB*/
                database = client.getDB(dbName);

                /*Generate  DB Bean*/
                DatabaseBean dbBean = new DatabaseBean();
                dbBean.setName(dbName);

                /*Add DB Bean to list*/
                databaseMap.add(dbBean);

                /*Create Collection List*/
                ArrayList<CollectionBean> collectionsList = new ArrayList<CollectionBean>();
                dbBean.setCollections(collectionsList);

                /*Put Collections to Database Bean*/
                for (String collectionName : database.getCollectionNames()) {
                    CollectionBean bean = new CollectionBean();
                    bean.setName(collectionName);
                    collectionsList.add(bean);
                }
            }
        }

        public ArrayList<DatabaseBean> getDatabaseMap() {
            return databaseMap;
        }

    }

}
